using Core;
using SuperSocket.Channel;
using SuperSocket.Command;

namespace Server;

public abstract class PlayAsyncCommand<TPackage> : IAsyncCommand<PlaySession, BaseCommand>
    where TPackage : BaseCommand
{
    protected abstract ValueTask HandlerAsync(PlaySession session, TPackage package);

    public async ValueTask ExecuteAsync(PlaySession session, BaseCommand package)
    {
        try
        {
            await HandlerAsync(session, (TPackage)package);
        }
        catch (Exception e)
        {
            session.LogError(e, $"执行命令：{package.Key} 抛出一个未知异常，关闭客户端");
            await session.CloseAsync(CloseReason.ApplicationError);
        }
    }
}

public abstract class PlayRespAsyncCommand<TPackage, TReplyPackage> : IAsyncCommand<PlaySession, BaseCommand> 
    where TPackage : BaseCommand
    where TReplyPackage : BaseCommand
{
    protected abstract ValueTask<TReplyPackage> HandlerAsync(PlaySession session, TPackage package);

    public async ValueTask ExecuteAsync(PlaySession session, BaseCommand command)
    {
        TReplyPackage replyCommand;

        try
        {
            replyCommand = await HandlerAsync(session, (TPackage)command);
        }
        catch (Exception e)
        {
            session.LogError(e, $"执行命令：{command.Key} 抛出一个未知异常，关闭客户端");
            await session.CloseAsync(CloseReason.ApplicationError);
            return;
        }

        await session.SendPacketAsync(replyCommand);
    }
}